#include "animatestackedwidget.h"

#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QPixmap>

AnimateStackedWidget::AnimateStackedWidget(QWidget *parent) : QStackedWidget(parent)
{
    m_label = new QLabel(this);
}

void AnimateStackedWidget::switchIndex(int newIdx)
{
    int oldIdx = currentIndex();
    if (oldIdx == newIdx || newIdx < 0 || newIdx >= count())
    {
        return;
    }

    int w = this->width();
    int h = this->height();

    QPixmap pixmap;
    // 将Widget的内容渲染到QPixmap对象中，即将Widget变成一张图片
    this->render(&pixmap);
    m_label->setPixmap(pixmap);
    m_label->setGeometry(0, 0, w, h);
    m_label->show();

    setCurrentIndex(newIdx);

    QPropertyAnimation *animation1 = new QPropertyAnimation(m_label, "pos");
    QPropertyAnimation *animation2 = new QPropertyAnimation(currentWidget(), "pos");
    animation1->setDuration(500);
    animation2->setDuration(500);
    animation1->setEasingCurve(QEasingCurve::OutCubic);
    animation2->setEasingCurve(QEasingCurve::OutCubic);

    if (oldIdx < newIdx)  //向左滑动
    {
        animation1->setStartValue(QPoint(0, 0));
        animation1->setEndValue(QPoint(0 - w, 0));
        animation2->setStartValue(QPoint(w, 0));
        animation2->setEndValue(QPoint(0, 0));
    }
    else  //向右
    {
        animation1->setStartValue(QPoint(0, 0));
        animation1->setEndValue(QPoint(w, 0));
        animation2->setStartValue(QPoint(0 - w, 0));
        animation2->setEndValue(QPoint(0, 0));
    }

    QParallelAnimationGroup *group = new QParallelAnimationGroup;
    group->addAnimation(animation1);
    group->addAnimation(animation2);
    group->start(QAbstractAnimation::DeleteWhenStopped);
    connect(group, SIGNAL(finished()), m_label, SLOT(hide()));
}
